using System.Windows;
using System.Windows.Controls;

namespace GraphMyCode.Client.Controls
{
	[TemplatePart(Name = "PART_EmptyText", Type = typeof(TextBlock))]
	[TemplatePart(Name = "PART_ClearButton", Type = typeof(Button))]
	[TemplatePart(Name = "PART_ClearButtonImage", Type = typeof(Image))]
	[TemplateVisualState(Name = "TextEmpty", GroupName = "TextStates")]
	[TemplateVisualState(Name = "TextNonEmpty", GroupName = "TextStates")]
	[TemplateVisualState(Name = "ButtonVisible", GroupName = "ClearButtonStates")]
	[TemplateVisualState(Name = "ButtonHidden", GroupName = "ClearButtonStates")]
	public class SearchBox : AutoCompleteBox
	{
		private TextBox textBox;
		private Button clearButton;

		public SearchBox()
		{
			DefaultStyleKey = typeof(SearchBox);
		}

		private Button ClearButton
		{
			set
			{
				if (clearButton != null)
					clearButton.Click -= ClearButton_Click;

				clearButton = value;

				if (clearButton != null)
					clearButton.Click += ClearButton_Click;
			}
		}

		public override void OnApplyTemplate()
		{
			base.OnApplyTemplate();
			ClearButton = GetTemplateChild("PART_ClearButton") as Button;
			textBox = GetTemplateChild("Text") as TextBox;
			UpdateStates(true);
		}

		protected override void OnTextChanged(RoutedEventArgs e)
		{
			base.OnTextChanged(e);
			UpdateStates(true);
		}

		protected override void OnGotFocus(RoutedEventArgs e)
		{
			base.OnGotFocus(e);
			UpdateStates(true);
		}

		protected override void OnLostFocus(RoutedEventArgs e)
		{
			base.OnLostFocus(e);
			UpdateStates(true);
		}

		private void ClearButton_Click(object sender, RoutedEventArgs e)
		{
			if (textBox != null)
				textBox.Text = string.Empty;
		}

		private void UpdateStates(bool useTransitions)
		{
			if (string.IsNullOrEmpty(Text) && !HasFocus())
				VisualStateManager.GoToState(this, "TextEmpty", useTransitions);
			else
				VisualStateManager.GoToState(this, "TextNonEmpty", useTransitions);

			if (string.IsNullOrEmpty(Text))
				VisualStateManager.GoToState(this, "ButtonHidden", useTransitions);
			else
				VisualStateManager.GoToState(this, "ButtonVisible", useTransitions);
		}
	}
}